package com.zzh.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

/**
 * @author zhangzhihao
 * @email zhangzhihao@gongjiangren.net
 * @date 2020-07-02
 * @desc
 */
public class LlReuseAddView extends LinearLayout {


    private Context mContext;
    private int mItemLayoutId;
    private OnAssignmentOperation onAssignmentOperation;

    public void setOnAssignmentOperation(OnAssignmentOperation onAssignmentOperation) {
        this.onAssignmentOperation = onAssignmentOperation;
    }

    public interface OnAssignmentOperation {
        void operation(LlReuseAddView llReuseAddView, View rootView, int position);
    }

    public LlReuseAddView(Context context) {
        this(context, null);
    }

    public LlReuseAddView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LlReuseAddView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        init(attrs);
    }

    private void init(@Nullable AttributeSet attrs) {
        TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.LlReuseAddView);
        mItemLayoutId = typedArray.getResourceId(R.styleable.LlReuseAddView_ItemLayout, -1);
        typedArray.recycle();
    }

    public void configCount(int count) {
        int childCount = getChildCount();
        if (childCount >= count) {
            for (int i = 0; i < childCount; i++) {
                View view = getChildAt(i);
                if (i >= count) {
                    view.setVisibility(View.GONE);
                } else {
                    view.setVisibility(View.VISIBLE);
                    sendView(view, i);
                }
            }
        } else {
            for (int i = 0; i < count; i++) {
                if (i < childCount) {
                    View view = getChildAt(i);
                    view.setVisibility(View.VISIBLE);
                    sendView(view, i);
                } else {
                    View view = LayoutInflater.from(mContext).inflate(mItemLayoutId, null, false);
                    addView(view);
                    sendView(view, i);
                }
            }
        }
    }

    private void sendView(View view, int position) {
        if (onAssignmentOperation != null) {
            onAssignmentOperation.operation(this,view, position);
        }
    }

}
